package storage

import (
	"log"
	"net/http"
	"net/url"
	"proxy_pool/entity"
	"strconv"
	"time"
)

// CheckIP is to check the ip work or not
func CheckIP(ip *entity.IPEntity) {
	// log.Println("check:   " + ip.Ip)
	//访问查看ip的一个网址
	httpUrl := "http://icanhazip.com"
	proxy, err := url.Parse("//" + ip.Ip + ":" + ip.Port)
	if err != nil {
		// log.Println(err)
		return
	}
	netTransport := &http.Transport{
		Proxy:                 http.ProxyURL(proxy),
		MaxIdleConnsPerHost:   10,
		ResponseHeaderTimeout: time.Second * time.Duration(5),
	}
	httpClient := &http.Client{
		Timeout:   time.Second * 10,
		Transport: netTransport,
	}
	res, err := httpClient.Get(httpUrl)
	if err != nil {
		// fmt.Println("错误信息：", err)
		return
	}
	defer res.Body.Close()
	if res.StatusCode != http.StatusOK {
		// log.Println(err)
		return
	}

	// 添加到全局变量里头  需要判断是否已经包含了
	if !IsContain(CheckedIps, ip) {
		CheckedIps = append(CheckedIps, ip)
	}
	log.Println("可用ip长度：" + strconv.Itoa(len(CheckedIps)))
}

func IsContain(items []*entity.IPEntity, item *entity.IPEntity) bool {
	for _, eachItem := range items {
		if eachItem.Ip == item.Ip && eachItem.Port == item.Port {
			return true
		}
	}
	return false
}
